package com.hbk.base.conf;

import com.hbk.base.component.EnvPostProcessor;
import com.hbk.base.component.ExternalConfig;
import com.hbk.base.interceptor.AuthInterceptor;
import com.hbk.base.interceptor.LoggerInterceptor;
import com.hbk.base.interceptor.LoggerUrlInerceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class CustomWebConfig implements WebMvcConfigurer {

    @Bean
    public LoggerUrlInerceptor loggerUrlInerceptor(){
        return new LoggerUrlInerceptor();
    }

    @Bean
    public LoggerInterceptor loggerInterceptor(){
        return new LoggerInterceptor();
    }
    @Bean
    public AuthInterceptor authInterceptor(){
        return new AuthInterceptor();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        ExternalConfig.EditorConfig editorConfig = EnvPostProcessor.getExternalConfig().getEditor();
        registry.addResourceHandler("/upload/**")
                .addResourceLocations("file:" + editorConfig.getImgDir());
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {


        /** 日志记录，记录所有的url请求，优先级 0 */
        //拦截的url
        List<String> logUrlPatterns = new ArrayList<>();
        logUrlPatterns.add("/**");

        registry.addInterceptor(loggerUrlInerceptor())
                .order(0)
                .addPathPatterns(logUrlPatterns);

        /** 日志记录，记录所有的 /api 的请求，优先级 1 */
        //拦截的url
        List<String> logPatterns = new ArrayList<>();
        logPatterns.add("/api/**");

        registry.addInterceptor(loggerInterceptor())
                .order(1)
                .addPathPatterns(logPatterns);

        /** token校验,优先级 2 */
        //拦截的url
        List<String> authPatterns = new ArrayList<>();
        authPatterns.add("/api/**");
        //过滤的url
        List<String> authExcludePatterns = new ArrayList<>();
        authExcludePatterns.add("/api/member/login");
        authExcludePatterns.add("/api/news/webList");
        authExcludePatterns.add("/api/consultation/webList");

        registry.addInterceptor(authInterceptor())
                .order(2)
                .addPathPatterns(authPatterns)
                .excludePathPatterns(authExcludePatterns);
    }


    /*
        过滤器需要放行的地址
        /api/news/webList
        /api/consultation/webList
        /api/member/login
     */
}
